//
//  MJTRefreshControl.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/16.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
//控件的高度
private let MJTRefreshControlHeight: CGFloat = 50
//下拉刷新的枚举类型
enum MJTRefreshControlState: Int {
    //下拉刷新状态
    case Normal = 0
    //送手就刷新
    case Pulling = 1
    //正在刷新
    case Refreshing = 2
}
class MJTRefreshControl: UIControl {

    // 当前下拉刷新的状态
    var refreshState: MJTRefreshControlState = .Normal {
        didSet {
            switch refreshState {
            case .Normal:
//                print("normal")
                //显示箭头,文字改变下拉刷新,风火轮停止,箭头重置
                iconImageView.hidden = false
                messageLabel.text = "下拉刷新"
                //停止转
                indicatorView.stopAnimating()
                //箭头重置
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                //只有上一次是刷新状态才可以回到原位置
                if oldValue == .Refreshing {
                    // 重置contentInset回到原始位置
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= MJTRefreshControlHeight
                    })
                }
            case .Pulling:
//                print("pulling")
                // 箭头调转,文本改成松手就刷新
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
//                print("refreshing")
                // 隐藏箭头,文本改为正在刷新,开启风火轮
                messageLabel.text = "正在刷新..."
                iconImageView.hidden = true
                //开启风火轮
                indicatorView.startAnimating()
                //停留在正在刷新,改变contentInset，设置内容间距,执行一个动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += MJTRefreshControlHeight
                })
                //  告诉外界刷新, 只有继承UIControl才能发送事件，uiview不可用
                sendActionsForControlEvents(.ValueChanged)
            }

        }
    }

    //  当前 滚动视图
    var currentScrollView: UIScrollView?
    //MARK: - 懒加载控件
    //下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //无敌风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
    //刷新文本
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.grayColor()
        label.text = "下拉刷新"
        return label
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加控件设置约束
    private func setupUI() {
        backgroundColor = RandomColor()
        //添加控件设置约束
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        //使用手动代码自动布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        indicatorView.startAnimating()
    }
    //将要添加到哪个父控件的时候去调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断其父控件是否能够滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        //到此视图移动能够滚动
        //设置自己的Frame
        self.frame.size = CGSize(width: scrollView.size.width, height: MJTRefreshControlHeight)
        self.frame.origin.y = -MJTRefreshControlHeight
        //使用kvo监听其父控件的滚动
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        currentScrollView = scrollView
    }
    //kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(currentScrollView?.contentOffset.y)
        //根据偏移量设置tableView进入不同的刷新状态
        guard let scrollView = currentScrollView else {
            return
        }
        //判断是否在拖动
        if scrollView.dragging {
            // 因为往下拉是偏移量变小
            if scrollView.contentOffset.y < -114 && refreshState == .Normal {
                //设置状态
                refreshState = .Pulling
            } else if scrollView.contentOffset.y > -114 && refreshState == .Pulling {
                //设置状态
                refreshState = .Normal
            }
        } else {
            if refreshState == .Pulling {
                refreshState = .Refreshing
            }
        }
    }
    //结束刷新
    func endRefreshing() {
        refreshState = .Normal
    }
    deinit {
        // 移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
